package com.yj.web.help;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created by a1 on 2017/3/1.
 */
public class PoUtil<T> {

    private static final String GET_PREFIX = "get";
    private static final String SET_PREFIX = "set";
    private static final String SPACE = "";
    private static final int ARRINDEX = 0;

    /**
     *
     * @param object 从页面传入的对象
     * @param pObj 从数据库取出的对象
     * @return
     * @throws Exception
     */
    public static void supplementPo(Object object, Object pObj) throws Exception {

        Class classType = object.getClass();
        Class pClassType = pObj.getClass();
        Field fields[] = pClassType.getDeclaredFields();
        Method[] m = pClassType.getDeclaredMethods();
        StringBuffer strvalu=new StringBuffer();
        for (int i = 0; i < fields.length; i++) {
            StringBuffer getMethodName = new StringBuffer(GET_PREFIX);
            StringBuffer setMethodName = new StringBuffer(SET_PREFIX);
            Field field = fields[i];
            String fieldName = field.getName();
            fieldName = fieldName.replaceFirst(fieldName.split(SPACE)[ARRINDEX], fieldName.split(SPACE)[ARRINDEX].toUpperCase());
            getMethodName.append(fieldName);
            Method getMethod = classType.getMethod(getMethodName.toString(), new Class[] {});
            Object value = getMethod.invoke(object, new Object[] {});

            if(value != null) {
                setMethodName.append(fieldName);
                field.setAccessible(true);
                Method setMethod = pClassType.getMethod(setMethodName.toString(), field.getType());
                setMethod.invoke(pObj, new Object[]{value});

            }
        }

    }
}
